import exp from "constants"
import {defineStore} from "pinia"
import {fetchSignIn, fetGetUserProfile} from "~/api/user"
import {ISigningParams, IUserProfile} from "~/api/user/types"
import {getJWTToken, setJWTToken, setUserProfile} from "~/request/utils"
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
interface IUserInfo {
    token: string,
        userInfo: IUserProfile
}

const userStore = defineStore('user', {
    state: (): IUserInfo => {
        return {
            token: "",
            userInfo: {
                user_id: 0,
                username: "",
                avatar: "",
                email: "",
                gender: 0,
            }
        }
    },
    actions: {
        async handleLogin(model: ISigningParams) {
            return new Promise<boolean>(async (resolve, reject) => {
                const params = {
                    username: model.username,
                    password: model.password
                }
                const res = await fetchSignIn(params)
                if (res.code === 1000) {
                    this.token = res.result
                    setJWTToken(`Bearer ` + this.token)
                    resolve(true)
                } else {
                    reject(false)
                }
            })
        },
        async handleGetUserProfile() {
            return new Promise(async (resolve, reject) => {
                const token = getJWTToken()
                if (token) {
                    const res = await fetGetUserProfile()
                    this.userInfo = res.result
                    // setUserProfile(res.result)
                    if (res.code === 1000) {
                        resolve(res.result)
                    } else {
                        reject({})
                    }
                } else {
                    reject({})
                }
            })
        }
    }
})
export default userStore;
